package at.ac.tuwien.mg.wh.client;

import java.util.ArrayList;
import java.util.List;

import javax.naming.InitialContext;

import org.activiti.engine.delegate.DelegateExecution;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import at.ac.tuwien.mg.bean.Item;
import at.ac.tuwien.mg.bean.Order;
import at.ac.tuwien.mg.wh.WarehouseBeanRemote;
import at.ac.tuwien.mg.wh.dto.DescribedItemDTO;
import at.ac.tuwien.mg.wh.dto.ItemDTO;
import at.ac.tuwien.mg.wh.exception.WarehouseException;

public class LookupClient extends Client {

	private static Logger log = LoggerFactory.getLogger(LookupClient.class);


	@Override
	public void execute(DelegateExecution execution) throws Exception {

		
		
		InitialContext ctx = new InitialContext();
		WarehouseBeanRemote bean = lookupStateless(ctx);
		
		///////////////////////////
		// FOR TESTING ONLY
		
		bean.cleanDdData();
		setDB(bean);
		//setInitBooked(bean);
		/*
		Init DB state
		
		silver = 0
		wood = 5
		gold = 10
		stone = 15	 setInitBooked() -> 7 booked (for user 100)	-> 8 free
		
		*/
		
		//////////////////////////
		
		List<ItemDTO> input = orderToItemList((Order) execution.getVariable("currentOrder"));
		List<Long> catalogIds = itemListToIdList(input);
		
		
		
		List<ItemDTO> freeItems = bean.getFreeItems(catalogIds);
		
		List<ItemDTO> toOrder = new ArrayList<ItemDTO>();
		List<ItemDTO> toBook = new ArrayList<ItemDTO>();
		
		for(ItemDTO freeItem :freeItems){
			for(ItemDTO inputItem :input){
				if(freeItem.getCatalogId().equals(inputItem.getCatalogId())){
					if(freeItem.getNumber().equals(new Integer(0))){
						toOrder.add(new ItemDTO(freeItem.getCatalogId(), inputItem.getNumber()));
					}else if(freeItem.getNumber() < inputItem.getNumber()){
						toBook.add(new ItemDTO(freeItem.getCatalogId(), freeItem.getNumber()));
						toOrder.add(new ItemDTO(freeItem.getCatalogId(), inputItem.getNumber()-freeItem.getNumber()));
					}else{
						toBook.add(new ItemDTO(freeItem.getCatalogId(), inputItem.getNumber()));
					}
				}	
			}
		}
		
		execution.setVariable("toOrder", toOrder);
		execution.setVariable("toBook", toBook);

		log("[LOOKUP]\nitems to order: "+toOrder+"\nitems to book:  "+toBook);
		
		///////////////////////////
		
		closeContext(ctx);
	}	

}
